using System;
using System.Collections.Generic;
using Less.Core;
using Less.Core.Model;

namespace Less.DAL
{
    /// <summary>
    /// An utility class to read and write LogEntries from / to a database
    /// </summary>
    internal class LogEntriesDAL : GenericDAL<LogEntry>
    {
        // TODO: Extract SQL sentences to ConfigSettings
        internal LogEntriesDAL(IDatabase database)
        : base(database, "LogEntries")
        {
        }

        internal LogEntriesDAL()
        : base(new Database(LessDatabaseUtils.LessConnectionStringName), "LogEntries")
        {

        }

        public List<LogEntry> SelectLast(int count)
        {
            List<LogEntry> list = null;
            list = Database.SelectList<LogEntry>(String.Format("SELECT TOP ({1}) * FROM {0} ORDER BY Created DESC", TableName, count));
            return list;
        }

        internal List<LogEntry> SelectBySeverity(EntrySeverities severity)
        {
            List<LogEntry> list = null;
            list = Database.SelectList<LogEntry>(String.Format("SELECT * FROM {0} WHERE Severity=@0 ORDER BY Created DESC", TableName), severity);
            return list;
        }

        internal List<LogEntry> SelectByMinSeverity(EntrySeverities minSeverity)
        {
            List<LogEntry> list = null;
            list = Database.SelectList<LogEntry>(String.Format("SELECT * FROM {0} WHERE Severity>=@0 ORDER BY Created DESC", TableName),
                minSeverity);
            return list;
        }

        internal List<LogEntriesBySeveritySummary> SelectLogEntriesBySeveritySummary()
        {
            List<LogEntriesBySeveritySummary> list = null;
            list = Database.SelectList<LogEntriesBySeveritySummary>(String.Format("SELECT Severity, count(Id) as Count, Max(Created) as LastMessage FROM {0} GROUP BY Severity ",
                TableName));
            return list;
        }

        public override List<string> Validate(object record)
        {
            if (record == null)
                return new List<string>() { "record is null" };
            LogEntry logEntry = record as LogEntry;
            if (logEntry != null)
            {
                logEntry.UserName = logEntry.UserName.Left(100);
                logEntry.MetricName = logEntry.MetricName.Left(100);
                logEntry.Source = logEntry.Source.Left(4000);
                logEntry.Message = logEntry.Message.Left(4000);
                logEntry.SystemData = logEntry.SystemData.Left(4000);
                if ( logEntry.MetricValue !=null ) logEntry.MetricValue = logEntry.MetricValue.ToString().Left(4000);
            }
            else
            {
                return new List<string>() { "record is not a logEntry" };
            }
            return base.Validate(record);
        }
    }
}